package imageProcessing.filter;

import imageProcessing.Duplicator;
import imageProcessing.ImageEvent;
import imageProcessing.ImageListener;

import java.awt.Rectangle;
import java.util.ArrayList;

import javax.media.jai.PlanarImage;

public class RoiFilter implements ImageListener{

	
	private ArrayList<ImageListener> _listeners;
	
	private int _x;
	private int _y;
	private int _width;
	private int _height;
	private PlanarImage _image;
	
	public RoiFilter(){
		_listeners = new ArrayList<ImageListener>();
		_image = null;
		_x = -1;
		_y = -1;
		_width = -1;
		_height = -1;
	}

	public void notifyListeners() {
		if(this.allRectValuesSet()){
			ImageEvent ie  = new ImageEvent(this, _image);
			ArrayList<ImageListener> copy = Duplicator.copyListeners(_listeners);
			for (ImageListener listener : copy) {
				listener.imageChanged(ie);
			}
		} 
	}
	
	public void addImageListener(ImageListener il){
		_listeners.add(il);
	}
	
	public void removeImageListener(ImageListener il){
		_listeners.remove(il);
	}
	@Override
	public void imageChanged(ImageEvent ie) {
		PlanarImage img = ie.getImage();
		// TODO: Add Filter-code here
		_image =  PlanarImage.wrapRenderedImage(img.getAsBufferedImage(new Rectangle(_x, _y, _width, _height)
		,img.getColorModel()));
		notifyListeners();
	}
	
	private boolean allRectValuesSet(){
		if(_x != -1 && _y != -1 && _width != -1 && _height != -1){
			return true;
		}
		return false;
	}
	
	 public int getX() {
			return _x;
		}

		public void setX(int x) {
			this._x = x;
		}

		public int getY() {
			return _y;
		}

		public void setY(int y) {
			this._y = y;
		}

		public int getWidth() {
			return _width;
		}

		public void setWidth(int w) {
			this._width = w;
		}

		public int getHeight() {
			return _height;
		}

		public void setHeight(int h) {
			this._height = h;
		}
}
